package com.dxtx.util;

import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.view.View;
import android.widget.ImageView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.FailReason.FailType;
import com.nostra13.universalimageloader.core.assist.ImageSize;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
//import com.nostra13.universalimageloader.utils.DiscCacheUtils;

/**
 * 加载图片的工具类
 */
public class ImageLoaderUtils {

    // 加载图片的参数option
    private DisplayImageOptions options;
    // 图片加载的监听器
    private DefaultImageLoadingListener imageLoadingListener;
    // 显示图片的控件
    private ImageView imageView;
    // 默认图片资源
    private int imageRes;
    // 是否处理为圆形图片
    private boolean isRound = false;
    // 图片的四角处理为圆角
    private int roundPx = 0;

    private static final int DEF_ROUND_PX = 40;

    public static final int MAX_IMAGE_SIZE = 2048;

    /**
     * 私有化构造方法
     */
    private ImageLoaderUtils(ImageView imageView, int imageRes) {
        this.imageView = imageView;
        this.imageRes = imageRes;
        initOptions();
        imageLoadingListener = new DefaultImageLoadingListener();
    }

    /**
     * 私有化构造方法 noCache
     */
    private ImageLoaderUtils(ImageView imageView, int imageRes, String tem) {
        this.imageView = imageView;
        this.imageRes = imageRes;
        initOptionsNoCache();
        imageLoadingListener = new DefaultImageLoadingListener();
    }

    /**
     * 私有化构造方法,增加圆形图片处理
     */
    private ImageLoaderUtils(ImageView imageView, int imageRes, boolean isRound) {
        this.imageView = imageView;
        this.imageRes = imageRes;
        this.isRound = isRound;
        roundPx = -1;
        initOptions();
        imageLoadingListener = new DefaultImageLoadingListener();
    }

    /**
     * 私有化构造方法,增加圆角图片处理
     * roundPx 圆角像素
     */
    private ImageLoaderUtils(ImageView imageView, int imageRes, int roundPx) {
        this.imageView = imageView;
        this.imageRes = imageRes;
        if (roundPx < 0) {
            roundPx = 0;
        }
        this.roundPx = roundPx;
        isRound = true;
        initOptions();
        imageLoadingListener = new DefaultImageLoadingListener();
    }

    /**
     * 获取类实例
     */
    public static ImageLoaderUtils getInstance(ImageView imageView, int imageRes) {
        return new ImageLoaderUtils(imageView, imageRes);
    }

    /**
     * 获取不使用缓存的类实例
     */
    public static ImageLoaderUtils getInstanceNoCacher(ImageView imageView, int imageRes) {
        return new ImageLoaderUtils(imageView, imageRes, "noCache");
    }

    /**
     * 获取类实例:加载成圆形图片
     */
    public static ImageLoaderUtils getInstance(ImageView imageView, int imageRes, boolean isRound) {
        return new ImageLoaderUtils(imageView, imageRes, isRound);
    }

    /**
     * 获取类实例:加载成圆角图片
     *
     * @param imageView
     * @param imageRes
     * @param roundPx   圆角图片的圆化像素,=0时使用默认,不能小于0
     * @return
     */
    public static ImageLoaderUtils getInstance(ImageView imageView, int imageRes, int roundPx) {
        return new ImageLoaderUtils(imageView, imageRes, roundPx);
    }

    /**
     * 加载图片
     */
    public void load(String picUrl) {
        if (picUrl == null || picUrl.isEmpty()) {
            FailReason t = new FailReason(FailType.UNKNOWN, new Throwable());
            imageView.setImageBitmap(null);
            imageLoadingListener.onLoadingFailed("url is null", imageView, t);
            return;
        }
        ImageLoader.getInstance().displayImage(picUrl, imageView, options, imageLoadingListener);
    }

    /**
     * 根据传入的图片大小压缩下载图片
     *
     * @param picUrl
     * @param picWidth
     * @param picHeight
     */
    public void load(String picUrl, int picWidth, int picHeight) {
        if (picUrl == null || picUrl.isEmpty()) {
            FailReason t = new FailReason(FailType.UNKNOWN, new Throwable());
            imageView.setImageBitmap(null);
            imageLoadingListener.onLoadingFailed("url is null", imageView, t);
            return;
        }

        // 图片过高或过宽需要进行压缩，否则部分手机无法显示
        if (picWidth > MAX_IMAGE_SIZE || picHeight > MAX_IMAGE_SIZE) {
            if (picWidth > picHeight) {
                picHeight = picHeight * MAX_IMAGE_SIZE / picWidth;
                picWidth = MAX_IMAGE_SIZE;
            } else {
                picWidth = picWidth * MAX_IMAGE_SIZE / picHeight;
                picHeight = MAX_IMAGE_SIZE;
            }
            ImageSize imageSize = new ImageSize(picWidth, picHeight);
            ImageLoader.getInstance().loadImage(picUrl, imageSize, options, imageLoadingListener);
        } else {
            ImageLoader.getInstance().displayImage(picUrl, imageView, options, imageLoadingListener);
        }
    }

    /**
     * 加载图片
     */
    public void load(String picUrl, ImageLoadingListener imageLoadingListener) {
        if (picUrl == null || picUrl.isEmpty()) {
            FailReason t = new FailReason(FailType.UNKNOWN, new Throwable());
            imageView.setImageBitmap(null);
            imageLoadingListener.onLoadingFailed("url is null", imageView, t);
            return;
        }
        if (imageView != null) {
            ImageLoader.getInstance().displayImage(picUrl, imageView, options, imageLoadingListener);
        }
    }

    /**
     * 初始化options
     */
    private void initOptions() {
        options = new DisplayImageOptions.Builder().showImageOnLoading(imageRes).showImageForEmptyUri(imageRes)
                .showImageOnFail(imageRes).cacheInMemory(true).cacheOnDisc(true).considerExifParams(true)
                .bitmapConfig(Config.RGB_565).build();
    }

    /**
     * 初始化options nocache
     */
    private void initOptionsNoCache() {
        options = new DisplayImageOptions.Builder().showImageOnLoading(imageRes).showImageForEmptyUri(imageRes)
                .showImageOnFail(imageRes).cacheInMemory(true).cacheOnDisc(false).considerExifParams(true)
                .bitmapConfig(Config.RGB_565).build();
    }

    /**
     * 默认加载完成的图片处理
     */
    private class DefaultImageLoadingListener implements ImageLoadingListener {

        @Override
        public void onLoadingCancelled(String arg0, View arg1) {
            imageView.setImageResource(imageRes);
        }
        @Override
        public void onLoadingComplete(String arg0, View view, Bitmap bitmap) {
            if (null != bitmap) {
                if (isRound) {
                    if (roundPx < 0) {
                        imageView.setImageDrawable(new CircleImageDrawable(bitmap));
                    } else if (roundPx == 0) {
                        imageView.setImageDrawable(new RoundedBitmapDisplayer.RoundedDrawable(bitmap, DEF_ROUND_PX, 0));
                    } else {
                        imageView.setImageDrawable(new RoundedBitmapDisplayer.RoundedDrawable(bitmap, roundPx, 0));
                    }
                }else{
                    imageView.setImageBitmap(bitmap);
                }
            } else {
                imageView.setImageResource(imageRes);
            }
        }

        @Override
        public void onLoadingFailed(String arg0, View arg1, FailReason arg2) {
            imageView.setImageResource(imageRes);
        }

        @Override
        public void onLoadingStarted(String arg0, View arg1) {
        }
    }

    /**
     * 将图片做成圆形,从中心取centerCrop,不失真
     *
     * @param bitmap
     * @return Bitmap edit by wx220755
     */
    public static Bitmap toCircleBitmap(Bitmap bitmap) {
        //创建宽高相等的空白画布
        Bitmap output = createCircleScaleBitmap(bitmap);
        Canvas canvas = new Canvas(output);

        //任意底色,底色仅作为过滤目标图像用
        int color = Color.GRAY;
        Paint paint = new Paint();
        Rect dest = new Rect(0, 0, output.getWidth(), output.getHeight());
        RectF destF = new RectF(dest);

        float roundPx = output.getHeight() / 2;
        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        //绘制圆形底色dst
        canvas.drawRoundRect(destF, roundPx, roundPx, paint);
        //设置 下次绘制时,模式为选取dst层有图像的部分
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        //获取centerCrop的源位置
        Rect src;
        int w = bitmap.getWidth();
        int h = bitmap.getHeight();
        if (w == h) {
            src = new Rect(0, 0, w, h);
        } else if (w > h) {
            src = new Rect((w - h) / 2, 0, (w + h) / 2, h);
        } else {
            src = new Rect(0, (h - w) / 2, w, (w + h) / 2);
        }
        canvas.drawBitmap(bitmap, src, dest, paint);
        return output;

    }


    /**
     * 创建缩放后的模板
     *
     * @param bitmap Bitmap 源位图
     * @return bitmap 空白位图
     */

    public static Bitmap scaleBitmap(Bitmap bitmap) {
        float width = bitmap.getWidth();
        float height = bitmap.getHeight();
        // 计算宽高缩放率
        float scaleWidth = 0;
        float scaleHeight = 0;
        if (width > height) {
            scaleWidth = 720 / width;
            scaleHeight = 480 / height;
        } else {
            scaleWidth = 720 / height;
            scaleHeight = 480 / width;
        }
        if (scaleWidth >= 1 && scaleHeight >= 1) {
            return Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);
        }
        float scale = Math.min(scaleWidth, scaleHeight);
        return Bitmap.createBitmap((int) (bitmap.getWidth() * scale), (int) (bitmap.getHeight() * scale),
                Config.ARGB_8888);
    }

    /**
     * 创建圆形模板
     *
     * @param bitmap
     * @return
     */
    public static Bitmap createCircleScaleBitmap(Bitmap bitmap) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();

        int size = Math.min(width, height);

        if (480 >= size) {
            return Bitmap.createBitmap(size, size, Config.ARGB_8888);
        } else {
            return Bitmap.createBitmap(480, 480, Config.ARGB_8888);
        }
    }


    

}
